package com.heima.kafka.stream;


import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.*;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * 消息处理
 */
public class KafkaStreamFastStart {
    public static void main(String[] args) {
        //1 kafka配置信息
        Properties prop = new Properties();
        prop.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.129:9092");
        prop.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-sample");

        //2 stream构建器
        StreamsBuilder builder = new StreamsBuilder();
        //流式计算
        streamProcessor(builder);

        //3 创建 kafkaStreams
        KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), prop);
        //4 开启kafka流计算
        System.out.println("streamProcessor start: ");
        kafkaStreams.start();
    }

    private static void streamProcessor(StreamsBuilder builder) {
        //接收生产者发送消息
        KStream<String, String> stream = builder.stream("itcast-topic-input");
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                // value 接收消息的具体内容
                System.out.println("消息内容：" + value);
                return Arrays.asList(value.split(" "));
            }
        })
                //根据value分组
                .groupBy((key, value) -> value)
                //聚合计算时间间隔
                .windowedBy(TimeWindows.of(Duration.ofSeconds(5)))
                //聚合查询:单词总数
                .count()
                //转成KStream
                .toStream()
                //处理后结果key和value转成string
                .map(new KeyValueMapper<Windowed<String>, Long, KeyValue<String, String>>() {
                    // 参数1：汇总后的key
                    // 参数2：实时计算结果
                    @Override
                    public KeyValue<String, String> apply(Windowed<String> key, Long value) {

                        System.out.println("汇总后的单词key: "+ key.key() +" ：" + value);
                        return new KeyValue<>(key.key().toString(), value.toString());
                    }
                })
                //处理后的结果转发给消费方
                .to("itcast-topic-output");
    }

}